<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div style="display: flex;">
                    <!-- <el-select style="width: 120px;" v-model="find_data.name1" placeholder="开始时间">
                        <el-option v-for="item in status_list" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select> -->
                    <div>
                        <el-date-picker :default-time="defaultTime" style="width: 340px;height:30px" v-model="timeTypeTime"
                        @change="timeTypeTime_btn" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                    </div>

                    <el-select style="width: 120px;margin-left: 10px;" v-model="find_data.orderBycondition" placeholder="">
                        <el-option  label="升序" :value="'0'" />
                        <el-option  label="降序" :value="'1'" />
                    </el-select>

                    <el-input type="text" style="width: 200px;margin-left: 10px;" v-model="find_data.find"
                    placeholder="行程详情/备注/订单号/航班号"  />
                    <el-input type="number" style="width: 100px;margin-left: 10px;" v-model="find_data.needSeats"
                    placeholder="座位数"  />
                    <el-input type="number" style="width: 100px;margin-left: 10px;" v-model="find_data.personNum"
                    placeholder="人数"  />
                    <el-select style="width: 120px;margin-left: 10px;" v-model="find_data.isShuttle" placeholder="降序">
                        <el-option  label="全部" value="" />
                        <el-option  label="接" value="0" />
                        <el-option  label="送" value="1" />
                    </el-select>
                    <el-select clearable style="width:220px;margin-left: 10px;" v-model="find_data.fromLocationId" placeholder="接站点">
                        <el-option v-for="item in getStationList_Data" :key="item.id" :label="item.station_name"
                        :value="item.id" />
                    </el-select>
                    <el-select clearable style="width: 220px;margin-left: 10px;" v-model="find_data.toLocationId" placeholder="送站点">
                        <el-option v-for="item in getStationList_Data" :key="item.id" :label="item.station_name"
                            :value="item.id" />
                    </el-select>
                    

                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <!-- <div style="margin-top:10px;display: flex;">
                    <el-button @click="add_btn" type="primary" icon="SuccessFilled">添加</el-button>
                    <el-button @click="up_btn" type="warning" icon="WarnTriangleFilled">修改</el-button>
                    <el-button @click="del_btn" type="danger" icon="CircleCloseFilled">删除</el-button>
                </div> -->
            </template>
            <div>
                <el-table border  @header-dragend='headerdragend' @selection-change="selection_change_btn" height="70.5vh" ref="multipleTableRef"
                    :data="list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <el-table-column width="100" label="操作">
                        <template #default="scope">
                            <el-button type="primary" size="small"
                                @click="handleset(scope.$index, scope.row)">抢单</el-button>

                        </template>
                    </el-table-column>
                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <template v-if="item.field == 'useCarCompanyId'" #="{ row, column, $index }">
                                <span>{{ row.realName ? row.realName + '-'+ row.mobile: row.useCarCompanyName?row.useCarCompanyName + '-'+ row.mobile :  row.mobile }}</span>
                            </template>
                            <template v-if="item.field == 'bankName'" #="{ row, column, $index }">
                                <div style="color:blue">起点：{{ row.fromLocation }}</div>
                                <div style="color:red">终点：{{ row.toLocation }}</div>
                            </template>

                            <template v-if="item.field == 'cardName'" #="{ row, column, $index }">
                                <span>{{ row.personNum + '人' }}/{{ row.needSeats ? row.needSeats + '座' : '不限座' }}</span>
                            </template>

                            <template v-if="item.field == 'cardName'" #="{ row, column, $index }">
                                <span>{{ row.personNum + '人' }}/{{ row.needSeats ? row.needSeats + '座' : '不限座' }}</span>
                            </template>
                            <template v-if="item.field == 'price'" #="{ row, column, $index }">
                                <span>{{ row.price.toFixed(2) }}元</span>
                            </template>
                            <template v-if="item.field == 'setime'" #="{ row, column, $index }">
                                <div class="c-green">开始：{{ row.startTime }}</div>
                                <div class="c-blue">结束：{{ row.endTime }}</div>
                            </template>


                        </el-table-column>
                    </template>


                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[20, 50, 100, 200]" :background="true" layout="prev, pager, next, jumper,->,sizes,total,"
                    :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:100px;z-index: 9999;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>

    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import { GET_TOKEN } from '@/utils/token.js'
import { ref, reactive, onMounted, computed } from 'vue'
import {
    adupPrivateSet, getPrivateSetList, getOrderReadyList, confirmGrabOrder,findStationCombo

} from '@/api/original_order_list.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { importCusCheckInData } from '@/utils/common.js'
import CircularJSON from 'circular-json'
onMounted(async () => {
    let order_grabbing_hall = JSON.parse(localStorage.getItem('order_grabbing_hall'))
    // if (account_management) {
    //     find_data.find = account_management.find
    // }
    findStationCombo({
        page: {
            pageNum: 1,
            pageSize: 999,
        },
        stationTypes: ['TRAIN', 'AIRPORT', 'BUS'],
    }).then(res => {
        if (res.code == 1) {
            getStationList_Data.value = res.data.list
        }
    })
    getPrivateSetList({
        find: '抢单大厅',
        page: {
            pageNum: 1,
            pageSize: 20,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            console.log('no')
            table_data_list_new.value = table_data_list
        }
    })


    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);
        }
    })


    timeTypeTime.value = [new_day(), to_day()]
    find_data.stime = new_day()
    find_data.etime = to_day()


    await list_api()

})
const new_day = () => {
    let today = new Date();

    let year = today.getFullYear();
    let month = today.getMonth() + 1; // 月份是从 0 到 11，所以需要加上 1
    let day = today.getDate();

    // 如果月份或日期小于 10，则在前面补零
    if (month < 10) {
        month = '0' + month;
    }

    if (day < 10) {
        day = '0' + day;
    }

    let formattedDate = `${year}-${month}-${day} 00:00:00`;
    return formattedDate
}
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
const to_day = () => {
    let today = new Date();
    let tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 30);

    let year = tomorrow.getFullYear();
    let month = tomorrow.getMonth() + 1; // 月份是从 0 到 11，所以需要加上 1
    let day = tomorrow.getDate();

    // 如果月份或日期小于 10，则在前面补零
    if (month < 10) {
        month = '0' + month;
    }

    if (day < 10) {
        day = '0' + day;
    }

    let formattedDate = `${year}-${month}-${day} 23:59:59`;
    return formattedDate
}
const getStationList_Data = ref([])
//#region 表格数据处理
const table_data_list = reactive([
    { label: '用车单位', field: 'useCarCompanyId', width: 220, off: true },
    { label: '行程详情', field: 'details', width: 220, off: true },
    { label: '起点/终点', field: 'bankName', width: 300, off: true },
    { label: '开始/结束时间', field: 'setime', width: 220, off: true },
    { label: '人数/座位数', field: 'cardName', width: 220, off: true },
    { label: '抢单价格', field: 'price', width: 220, off: true },
    { label: '航班号', field: 'flightNum', width: 220, off: true },
    { label: '备注', field: 'remark', width: 220, off: true },
    { label: '添加时间', field: 'addTime', width: 170, off: true },

])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '抢单大厅',
        tbNum: "order_grabbing_hall",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion

const status_list = reactive(
    [{
        value: 'READY_CAR',
        label: '未派车',
    },
    {
        value: 'CAR_READY_CONFIRME',
        label: '待确认(未确认派车)',
    },
    {
        value: 'DRIVER_READY_RECEIVE',
        label: '待接单(师傅未确认)',
    },
    {
        value: 'READY_ROAD',
        label: '未出行',
    }, {
        value: 'ON_ROADING',
        label: '未完团(在途)',
    }, {
        value: 'FINISHED',
        label: '完成',
    },]
)
const timeTypeTime = ref('')
const timeTypeTime_btn = (e) => {
    if (e) {
        timeTypeTime.value = e
        find_data.startTime = timeTypeTime.value[0]
        find_data.endTime = timeTypeTime.value[1]
    } else {
        timeTypeTime.value = ''
        find_data.startTime = ''
        find_data.endTime = ''
    }
}
//#region 分页列表
const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    startTime: '',
    endTime: '',
    status: '',
    routeSimpleName: '',
    orderBycondition:'1',
    personNum: '',
    needSeats:'',
    isShuttle: '',
    fromLocationId: '',
    toLocationId:'',
    find:'',
    name1:'',
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {
    const loading = ElLoading.service({
    lock: true,
    text: '正在加载，中请稍后...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
    getOrderReadyList(find_data).then(res => {
        loading.close()
        list_data.value = res.data.list
        total.value = res.data.total

    })
}
//#endregion


// 抢单
const handleset = (e, y) => {
    let luser = JSON.parse(localStorage.getItem("luser"))
    ElMessageBox.confirm(
        '确认抢单?',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            let ps = []
            for (let i = 0; i < table_list.value.length; i++) {
                ps.push(table_list.value[0].id)
            }

            confirmGrabOrder({
                id: y.id,
                userId: luser.uname,
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {


        })

}

//#region 表格选择
const table_list = ref([])
const headerdragend = (newWidth,oldWidth,column) =>{
    console.log(newWidth,oldWidth,column)
    for(let i =0;i<table_data_list_new.value.length;i++){
        if (column.property == table_data_list_new.value[i].field) {
            table_data_list_new.value[i].width = newWidth
        }
    }
}
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion

//#region 搜索
const search_btn = () => {
    localStorage.setItem('order_grabbing_hall', CircularJSON.stringify(find_data))
    list_api()
}
//#endregion


</script>

<style scoped lang='scss'>
</style>

<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}


.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
